package com.ce.server.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ce.server.common.RespBean;
import com.ce.server.common.RespPageBean;
import com.ce.server.mapper.NationMapper;
import com.ce.server.pojo.*;
import com.ce.server.service.*;
import com.ce.server.util.AdminUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 郑爽
 * @since 2021-11-17
 */
@RestController
@RequestMapping("/student")
public class StudentController {

  @Autowired
  private IStudentService studentService;
  @Autowired
  private INationService nationService;
  @Autowired
  private IPoliticsStatusService politicsStatusService;
  @Autowired
  private IOperlogService operlogService;
  @Autowired
  private IAdminRoleService adminRoleService;

  @Autowired
  private NationMapper nationMapper;

  @Value("${type.student}")
  private String type;


  @ApiOperation(value = "根据学号获取学生信息")
  @GetMapping("/{sno}")
  public RespBean getStudentBySno(@PathVariable("sno") String sno) {
    return studentService.getStudentBySnoVo(type + sno);

  }

  @ApiOperation("分页处理获取所有学生信息")
  @GetMapping("/")
  public RespPageBean getStudentsByPage(@RequestParam(defaultValue = "1") Integer currentPage,
                                        @RequestParam(defaultValue = "10") Integer size,
                                        Student student) {
    return studentService.getStudentsByPage(currentPage, size, student);
  }

  @ApiOperation(value = "更新学生信息")
  @PutMapping("/")
  public RespBean updateStuInfo(@RequestBody Student student) {

    if (studentService.update(student, new LambdaQueryWrapper<Student>().eq(Student::getSno, student.getSno()))) {
      Admin currentAdmin = (Admin) AdminUtil.getCurrentAdmin();
      operlogService.save(new Operlog().setWno(currentAdmin.getWno())
              .setWname(currentAdmin.getWname())
              .setOper("更新了学生信息").setOpertime(LocalDateTime.now()));
      return RespBean.success("更新信息成功！");
    }
    return RespBean.error("更新学生信息失败！");
  }

  @ApiOperation(value = "添加学生信息")
  @PostMapping("/")
  public RespBean addStuInfo(@RequestBody Student student) {
      if (student!=null){
        student.setSno("stu_"+student.getSno());
      }
    if (studentService.addStuInfo(student)) {
      Admin currentAdmin = (Admin) AdminUtil.getCurrentAdmin();
      operlogService.save(new Operlog().setWno(currentAdmin.getWno())
              .setWname(currentAdmin.getWname())
              .setOper("添加了学生信息").setOpertime(LocalDateTime.now()));
      return RespBean.success("添加学生信息成功！");
    }
    return RespBean.error("添加学生信息失败！");
  }

  @ApiOperation(value = "删除学生信息")
  @DeleteMapping("/{id}")
  public RespBean delStuInfo(@PathVariable("id") String sno) {
    if (studentService.remove(new LambdaUpdateWrapper<Student>().eq(Student::getSno, sno))){
      Admin currentAdmin = (Admin) AdminUtil.getCurrentAdmin();
      operlogService.save(new Operlog().setWno(currentAdmin.getWno())
              .setWname(currentAdmin.getWname())
              .setOper("删除了学生信息").setOpertime(LocalDateTime.now()));
      return RespBean.success("删除学生信息成功！");
    }
    return RespBean.error("删除学生信息失败！");
  }

  @ApiOperation(value = "批量删除学生信息")
  @DeleteMapping("/")
  public RespBean delStuBatch(String[] snos) {
    Integer record = studentService.delStuBatch(snos);
    if (record > 0){
      Admin currentAdmin = (Admin) AdminUtil.getCurrentAdmin();
      operlogService.save(new Operlog().setWno(currentAdmin.getWno())
              .setWname(currentAdmin.getWname())
              .setOper("批量删除了学生信息").setOpertime(LocalDateTime.now()));
      return RespBean.success("批量删除学生信息成功！", record);
    }
    return RespBean.error("批量删除学信息失败！");
  }

  @ApiOperation(value = "导出学生数据")
  @GetMapping(value = "/export", produces = "application/octet-stream")
  public void exportStudents(HttpServletResponse response) {
    List<Student> student_list = studentService.getStuRecords();
    ExportParams exportParams = new ExportParams("学生信息表", "学生信息表", ExcelType.HSSF);
    // 导出工具类
    Workbook workbook = ExcelExportUtil.exportExcel(exportParams, Student.class, student_list);
    ServletOutputStream outputStream = null;
    try {
      // 用流的形式传输
      response.setHeader("content-type", "application/octet-stream");
      // 防止中文乱码
      response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("学生信息表.xls", "UTF-8"));
      outputStream = response.getOutputStream();
      workbook.write(outputStream);

      Admin currentAdmin = (Admin) AdminUtil.getCurrentAdmin();
      operlogService.save(new Operlog().setWno(currentAdmin.getWno())
              .setWname(currentAdmin.getWname())
              .setOper("批量导出了学生信息").setOpertime(LocalDateTime.now()));

    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (null != outputStream) {
        try {
          outputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }

  @ApiOperation(value = "导入学生数据")
  @PostMapping("/import")
  public RespBean importStudent(MultipartFile file) {
    ImportParams importParams = new ImportParams();
    // 去掉第一行标题
    importParams.setTitleRows(1);
    // 获取实体数据
    List<Nation> nation_list = nationService.list();
    List<PoliticsStatus> politicsStatus_list = politicsStatusService.list();

    try {
      List<Student> list = ExcelImportUtil.importExcel(file.getInputStream(), Student.class, importParams);
      list.forEach(student -> {
        student.setSno(type+student.getSno());
        student.setNationId(nationService.getOne(new LambdaQueryWrapper<Nation>().eq(Nation::getName, student.getNation().getName())).getId());
        student.setPoliticId(politicsStatusService.getOne(new LambdaQueryWrapper<PoliticsStatus>().eq(PoliticsStatus::getName, student.getPoliticsStatus().getName())).getId());
        adminRoleService.save(new AdminRole().setNo(type+student.getSno()).setRid(3));
      });
      if (studentService.saveBatch(list)) {
        Admin currentAdmin = (Admin) AdminUtil.getCurrentAdmin();
        operlogService.save(new Operlog().setWno(currentAdmin.getWno())
                .setWname(currentAdmin.getWname())
                .setOper("批量导入了学生信息").setOpertime(LocalDateTime.now()));
        return RespBean.success("数据插入成功！");
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
    return RespBean.error("数据插入失败！");
  }

  @ApiOperation(value = "检查该学号是否存在")
  @GetMapping("/recheck—sno/{sno}")
  public Map<String,Object> recheck(@PathVariable("sno") String sno) {
    return studentService.recheckSno(sno);
  }
}
